import * as API from '@/services';
import { DEFAULT_FORM_LAYOUT, EntityId, KfBizQuickFormProps, KfFloatingContextProps, KfInput, KfQuickForm, KfUpload } from 'kf-web-library';
import { Form } from 'antd';
import React, { FunctionComponent } from 'react';
import KfMaterialUpload from "@/components/KfMaterialUpload";

const FormItem = Form.Item;
type QueryEntity = API.JournalTemplate;
type CreateEntity = API.JournalTemplate_Create;
type ModifyEntity = API.JournalTemplate_Modify;

type DataFormProps = {
  journalId?: EntityId;
} & KfBizQuickFormProps &
  KfFloatingContextProps;

const QuickForm: FunctionComponent<DataFormProps> = (props) => {
  const { formType, bizId, journalId, ...rest } = props;
  const [formInstance] = Form.useForm();

  return (
    <KfQuickForm
      formType={formType}
      formProps={{
        ...DEFAULT_FORM_LAYOUT,
        form: formInstance,
        onValuesChange: (changedValues, allValues) => {
          if (changedValues.fileUrl) {
            const url = new URL(changedValues.fileUrl);
            const searchParams = url.searchParams;
            //展示文件名要么从参数从获取, 要不就使用 url最后的一段
            const filename = searchParams.get('originalFilename') || url.pathname.split('/').pop();
            if (!allValues.nameCn) formInstance.setFieldValue('nameCn', filename);
            if (!allValues.nameEn) formInstance.setFieldValue('nameEn', filename);
          }
        },
      }}
      defaultQueryRequest={() =>
        API.queryJournalTemplate(bizId!).then((resp) => {
          if (resp.flag) {
            resp.data = {
              ...resp.data,
            } as any;
          }
          return new Promise((resolve) => resolve(resp));
        })
      }
      submitRequest={{
        create: (formValues) => API.createJournalTemplate({ journalId, seq: 1, ...formValues } as CreateEntity),
        modify: (formValues) => API.modifyJournalTemplate({ ...formValues, seq: 1, id: bizId } as ModifyEntity),
      }}
      {...rest}
    >
      <FormItem name={nameof<ModifyEntity>((x) => x.fileUrl)} label="文件" rules={[{ required: true }]}>
        {/*<KfUpload.Text maxCount={1} />*/}
        <KfMaterialUpload.Rapid materialType={'FILE'} maxCount={1}/>
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.nameCn)} label="中文名称" rules={[{ required: true }]}>
        <KfInput />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.nameEn)} label="中文名称" rules={[{ required: true }]}>
        <KfInput />
      </FormItem>
    </KfQuickForm>
  );
};

export default QuickForm;
